<template>
	<view class="page bg-fff">
        <up-form :model="form" label-width="auto" ref="newsForm">
            <up-form-item label="图片">
                <view class="picWrap">
                    <view class="imgWrap flex" @click="uploadImgBtn('pic')">
                        <block v-if="form.pic[0]?.url">
                            <image class="imgItem" :src="form.pic[0].url" mode="aspectFill"></image>
                        </block>
                        <block v-else>
                            <!-- #ifdef MP-WEIXIN || MP-TOUTIAO -->
                            <text class="ipang-add font35"></text>
                            <!-- #endif -->
                            <!-- #ifdef MP-BAIDU -->
                            <up-icon name="plus" color="#999999" size="35"></up-icon>
                            <!-- #endif -->
                        </block>
                    </view>
                </view>
            </up-form-item>

            <up-form-item label="标题" prop="title">
                <up-input v-model="form.title" placeholder="请输入标题" />
            </up-form-item>

            <up-form-item label="内容" prop="content">
                <up-textarea v-model="form.content" placeholder="请输入内容" maxlength="9999" autoHeight height="100"></up-textarea>
            </up-form-item>
            
            <up-form-item label="二维码显示">
                <view class="switchWrap flex">
                    <up-switch v-model="form.show_qrcode" active-color="#faa000"></up-switch>
                </view>
            </up-form-item>
        </up-form>
        <view class="btns">
            <button class="submitBtn bg-theme col-fff font15 clearBtn" @click="submitNews">提交</button>
            <button class="submitBtn top-15 bg-error col-fff font15 clearBtn" @click="deleteNews" v-if="form.id">删除</button>
        </view>

        <up-modal :show="showPrivacy" title="用户隐私保护提示" :show-confirm-button="false" @close="showPrivacy=false">
            <privacy-authorize @close="closePrivacyModal"></privacy-authorize>
        </up-modal>
	</view>
</template>
<script>
    import { mapState } from 'pinia';
    import { useUserInfoStore, useIndexStore } from '@/store/index';
    import { checkLogin, checkUserInfo, checkWXPrivacyAuthorize, uuid, getFileType, upload_image, isBoolean } from '@/common/common';
    import { checkUploadParamsByType } from '@/common/utils/check';
    import { newsEditAPI, newsAddAPI, newsDeleteAPI } from '@/common/api/houses';
	export default {
		data() {
			return {
                form: {
                    pic: [],
                    title: '',
                    content: '',
                    show_qrcode: true,
                    city_code: ''
                },
                showPrivacy: false,
                rules: {
                    title: [
                        {
                            required: true,
                            message: '请输入标题',
                            trigger: 'blur,change'
                        }
                    ],
                    content: [
                        {
                            required: true,
                            min: 5,
                            message: '不能少于5个字',
                            trigger: 'change'
                        }
                    ]
                }
			}
		},
        onReady() {
            this.$refs.newsForm.setRules(this.rules);
        },
		onLoad(options) {
            const that = this;
            if(options.info) {
                let { title, content, show_qrcode=true, id, city_code } = JSON.parse(decodeURIComponent(options.info));
                this.form.title = title;
                this.form.content = content;
                this.form.show_qrcode = isBoolean(show_qrcode);
                this.form.id = id;
                this.form.city_code = city_code;
            }else {
                this.form.city_code = this.nowCityCode;
            }
            // if(this.userInfo && !this.userInfo.tips) {
            //     uni.showModal({
            //     	title: '提示',
            //     	content: '您没有权限打开此页面',
            //         showCancel: false,
            //     	success: function (res) {
            //     		if (res.confirm) {
            //                 uni.navigateBack({
            //                     delta: 1
            //                 })
            //     		}
            //     	}
            //     });
            // }
            uni.$check_and_login(function() {
                that.init();
            })
		},
        computed:{
            ...mapState(useIndexStore, ['nowCityCode', 'uploadParam']),
            ...mapState(useUserInfoStore, ['userInfo'])
        },
		methods: {
            //初始化
            async init() {
                await checkUploadParamsByType('public');
            },

            //上传图片
            async uploadImgBtn(type) {
                const that = this;

                if (!checkLogin()) {
                    uni.navigateTo({
                        url: '/pages/login/login'
                    })
                    return
                }
                if (!checkUserInfo()) {
                    uni.navigateTo({
                        url: `/pages/login/user-info-form`
                    })
                    return
                }

                let privacyRes = await checkWXPrivacyAuthorize();
                if (privacyRes) {
                    this.showPrivacy = true;
                    return
                }

                uni.chooseMedia({
                    count: 1, //默认9
                    mediaType: ['image'],
                    success: (res) => {
                        let fileObj = {};
                        res.tempFiles.forEach(item => {
                            let name = `broker/${that.userInfo.id}/${uuid()}${getFileType(item.tempFilePath)}`;
                            fileObj = { url: item.tempFilePath, key: name }
                        })
                        //如果是上传卡片,使用卡片的上传参数
                        upload_image(that.uploadParam['public'], fileObj.url, fileObj.key, function (res, key) {
                            that.form[type] = [fileObj];
                        });
                    }
                })
            },

            //关闭隐私政策模态框
            closePrivacyModal() {
                this.showPrivacy = false;
            },
            
            //提交
            submitNews() {
                const that = this;
                this.$refs.newsForm.validate().then(async valid => {
                    if (valid) {
                        uni.showLoading({
                            title: 'loading'
                        })
                        let succRes=null;
                        if(this.form.id) {
                            succRes = await newsEditAPI(this.form);
                        }else {
                            succRes = await newsAddAPI(this.form);
                        }
                        uni.hideLoading();
                        if(succRes.status === 0) {
                            uni.$common.msg('操作成功');
                            setTimeout(function() {
                                uni.redirectTo({
                                    url: `/pages/follow/news/news-list?city=${that.nowCityCode}`
                                })
                            }, 1000)
                        }else {
                            uni.$common.msg(succRes.detail);
                        }
                    }
                });
            },
            
            //删除
            deleteNews() {
                const that = this;
                uni.showModal({
                	title: '提示',
                	content: '确认删除该快报?',
                	success: function (res) {
                		if (res.confirm) {
                            newsDeleteAPI(that.form.id).then(delRes => {
                                if(delRes.status === 0) {
                                    uni.$common.msg('删除成功');
                                    setTimeout(function() {
                                        uni.redirectTo({
                                            url: `/pages/follow/news/news-list?city=${that.nowCityCode}`
                                        })
                                    }, 1000)
                                }else {
                                    uni.$common.msg(delRes.detail);
                                }
                            });
                		}
                	}
                });
            }
		}
	}
</script>

<style lang="scss" scoped>
	.page{
        line-height: 1.3;
		min-height: 100vh;
        overflow: hidden;
        padding: 10rpx 28rpx;
        .switchWrap{
            justify-content: flex-end;
        }
        .picWrap {
            .imgWrap {
                width: 120rpx;
                height: 120rpx;
                border: 1rpx dashed #999999;
                border-radius: 10rpx;
                overflow: hidden;
                position: relative;

                .imgItem {
                    width: 100%;
                    height: 100%;
                }
            }
        }
        .btns{
            position: fixed;
            z-index: 10;
            left: 28rpx;
            bottom: 50rpx;
            width: calc(100% - 56rpx);
            .submitBtn{
                height: 80rpx;
                line-height: 80rpx;
                border-radius: 20rpx;
            }
        }
	}
</style>